<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/6/6 0006
 * Time: 15:51
 */
namespace app\api\controller;
use app\models\Models;

class Order extends Base {
    /**
     * 我的订单
     * @return \think\response\Json
     */
    public function myOrder(){
        if(request()->isPost()){
            try{
                // 登录验证
                $params = self::checkLogin(['equipment','encrypt']);
                $order = new Models('order');
                $join  = [['business b','a.bid = b.id','left'],['order_goods c','a.id = c.oid','left'],['goods d','c.gid = d.id','left'],['goods e','c.cid = e.id','left']];
                $where = ['a.status'=>Models::ORDER_PAY_NOT,'a.uid'=>$params['uid']];
                $list = $order->joinMany($join,$where,'a.order_no,b.name business,a.status,a.create_time,a.pay_amount,c.qty,d.name goods_name,d.price goods_price,e.name combo_name,e.price combo_price');
                foreach($list as $k=>$v){
                    $arr[$v['order_no']]['order_no'] = $v['order_no'];
                    $arr[$v['order_no']]['business'] = $v['business'];
                    $arr[$v['order_no']]['status']   = $v['status'];
                    $arr[$v['order_no']]['create_time'] = $v['create_time'];
                    $arr[$v['order_no']]['goods'][$k]['name']  = empty($v['goods_name']) ? $v['combo_name'] : $v['goods_name'];
                    $arr[$v['order_no']]['goods'][$k]['price'] = empty($v['goods_name']) ? $v['combo_price'] : $v['goods_price'];
                    $arr[$v['order_no']]['goods'][$k]['qty']   = $v['qty'];
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($arr));
        }
    }

    /**
     * 购买酒水订单
     * 第一步选座并购买商品并下单
     * 第二步选择营销
     * 第三步选择支付方式并支付
     * @return \think\response\Json
     */
    public function wineOrderAdd(){
        $tran = new Models();
        if(request()->isPost()){
            try{
                // 登录验证
                $params = self::checkLogin(['equipment','encrypt','table_id','goods']);
                // 检查是否有未支付订单
                $order = new Models('order');
                $order_info = $order->_find(['uid'=>$params['uid'],'type_id'=>Models::ORDER_TYPE_WINE,'status'=>Models::ORDER_PAY_NOT]);
                if($order_info){
                    throw new \LogicException('您有酒水订单尚未支付，请前往支付或取消',1032);
                }
                // 获取桌号信息
                $table_info = self::getTableInfo($params['table_id']);
                if($table_info['lowest_cost'] > $params['order_amount']){
                    throw new \LogicException('您的消费低于该桌最低消费',1029);
                }
                if($table_info['status'] == Models::STATUS_OFF){
                    throw new \LogicException('该桌尚未开放，请重新选择',1034);
                }
                if($table_info['is_reserve'] == Models::TABLE_YES){
                    throw new \LogicException('该桌已被预订,请重新选择',1027);
                }
                //开启事务
                $tran->startTrans();
                $table = new Models('table');
                // 下单前预定座位，添加预定次数
                $bool = $table->_save(['id'=>$params['table_id'],'is_reserve'=>Models::TABLE_YES,'reserve_num'=>['exp','reserve_num+1']]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
                // 订单表添加纪录
                $params['bid']     = $table_info['bid'];
                $params['type_id'] = Models::ORDER_TYPE_WINE;
                $oid = self::orderAdd($params);
                // 订单商品关系表插入记录
                $params['oid'] = $oid;
                self::orderGoodsAdd($params);
            } catch (\Exception $e){
                $tran->rollback();
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            $tran->commit();
            return json(self::formatSuccessResult(['order_id'=>$oid]));
        }
    }

    /**
     * 活动酒水订单
     * @return \think\response\Json
     */
    public function activityOrderAdd(){
        $tran = new Models();
        if(request()->isPost()){
            try{
                // 登录验证
                $params = self::checkLogin(['equipment','encrypt','activity_id','goods']);
                // 检查是否有未支付订单
                $order = new Models('order');
                $order_info = $order->_find(['uid'=>$params['uid'],'type_id'=>Models::ORDER_TYPE_EVENT,'status'=>Models::ORDER_PAY_NOT]);
                if($order_info){
                    throw new \LogicException('您有活动订单尚未支付，请前往支付或取消',1032);
                }
                // 检查活动是否存在
                $activity = new Models('activity');
                $info = $activity->_find(['id'=>$params['activity_id']],'id,uid,bid,table_id,join_action,join_min,status');
                if(!$info || $info['status'] != Models::STATUS_OFF){
                    throw new \LogicException('活动不存在或已开始',1030);
                }
                // 获取桌号信息
                $table_info = self::getTableInfo($info['table_id']);
                // 获取个人最低消费金额
                $lowest_cost = $info['join_action'] == Models::MONEY_AA ? ($table_info['lowest_cost']/$info['join_min']) : $table_info['lowest_cost'];
                if($lowest_cost > $params['order_amount']){
                    throw new \LogicException('您的消费低于该桌最低消费',1029);
                }
                if($table_info['status'] == Models::STATUS_OFF){
                    throw new \LogicException('该桌尚未开放，请重新选择',1034);
                }
                if($table_info['is_reserve'] == Models::TABLE_YES){
                    throw new \LogicException('该桌已被预订,请重新选择',1027);
                }
                //开启事务
                $tran->startTrans();
                $table = new Models('table');
                // 下单前预定座位，添加预定次数
                $bool = $table->_save(['id'=>$info['table_id'],'is_reserve'=>Models::TABLE_YES,'reserve_num'=>['exp','reserve_num+1']]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
                // 订单表添加纪录
                $info['order_amount']  = $params['order_amount'];
                $info['type_id']       = Models::ORDER_TYPE_EVENT;
                $info['is_originator'] = Models::IS_ORIGINATOR;  // 发起人
                $oid = self::orderAdd($info);
                // 订单商品关系表插入记录
                $params['oid'] = $oid;
                self::orderGoodsAdd($params);
            } catch (\Exception $e){
                $tran->rollback();
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            $tran->commit();
            return json(self::formatSuccessResult(['order_id'=>$oid]));
        }
    }

    /**
     * 参加活动酒水订单
     * @return \think\response\Json
     */
    public function activityJoin(){
        $tran = new Models();
        if(request()->isPost()){
            try{
                // 登录验证
                $params = self::checkLogin(['equipment','encrypt','activity_id','goods']);
                // 检查活动是否存在
                $activity = new Models('activity');
                $info = $activity->_find(['id'=>$params['activity_id']],'id,uid,bid,table_id,join_action,join_min,status');
                if(!$info || $info['status'] != Models::STATUS_READY){
                    throw new \LogicException('活动不存在或已开始',1030);
                }
                // 获取桌号信息
                $table_info = self::getTableInfo($info['table_id']);
                // 获取个人最低消费金额
                $lowest_cost = $info['join_action'] == Models::MONEY_AA ? ($table_info['lowest_cost']/$info['join_min']) : 0;
                if($lowest_cost > $params['order_amount']){
                    throw new \LogicException('您的消费低于该桌最低消费',1029);
                }
                //开启事务
                $tran->startTrans();
                // 订单表添加纪录
                $order = new Models('order');
                $params['sid'] = $order->getValue(['aid'=>$params['activity_id'],'status'=>Models::STATUS_ON],'sid');
                $params['id']       = $params['activity_id'];
                $params['bid']      = $info['bid'];
                $params['table_id'] = $info['table_id'];
                $params['type_id']  = Models::ORDER_TYPE_EVENT;
                $oid = self::orderAdd($params);
                // 订单商品关系表插入记录
                $params['oid'] = $oid;
                self::orderGoodsAdd($params);
            } catch (\Exception $e){
                $tran->rollback();
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            $tran->commit();
            return json(self::formatSuccessResult(['order_id'=>$oid]));
        }
    }

    /**
     * 充值
     * @return \think\response\Json
     */
    public function recharge(){
        if(request()->isPost()){
            try{
                $params = self::checkLogin(['equipment','encrypt']);
                $recharge = new Models('recharge_type');
                $params['order_amount'] = $recharge->getValue(['id'=>$params['product_id'],'status'=>Models::STATUS_ON],'price');
                // 订单表添加纪录
                $params['type_id'] = Models::ORDER_TYPE_RECHARGE;
                $params['sid'] = 0;
                $oid = self::orderAdd($params);
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult(['order_id'=>$oid]));
        }
    }

    /**
     * 取消订单
     * @return \think\response\Json
     */
    public function cancelOrder(){
        if(request()->isPost()){
            try{
                // 登录验证
                $params = self::checkLogin(['equipment','encrypt']);
                $order = new Models('order');
                $info = $order->_find($params['order_id']);
                if($info['status'] == Models::ORDER_CANCEL){
                    throw new \LogicException('订单已取消',1042);
                }
                $bool = $order->_save(['id'=>$params['order_id'],'status'=>Models::ORDER_CANCEL]);
                $table = new Models('table');
                $bool1 = $table->_save(['reserve_num'=>['exp','reserve_num-1'],'status'=>Models::TABLE_NOT],['id'=>$info['table_id'],'status'=>Models::TABLE_YES]);
                if(!$bool || false === $bool1){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult());
        }
    }

    /**
     * 退款
     * @return \think\response\Json
     */
    public function refund(){
        if(request()->isPost()){
            try{
                $params = self::checkLogin(['equipment','encrypt']);
                $order = new Models('order');
                $info = $order->_find(['id'=>$params['order_id'],'status'=>Models::ORDER_PAY_YES]);
                if(!$info){
                    throw new \LogicException('订单不存在',1036);
                }
                if($info['pay_method'] == Models::PAY_ALIPAY){
                    // 支付宝退款
                    $alipay = new AliPay();
                    $result = $alipay->aliRefund($info['order_no'],$info['trade_no'],$info['pay_amount']);
                    if(!empty($result) && $result == 10000){
                        // 成功

                    } else {
                        throw new \LogicException('操作失败',1010);
                    }
                }
                if($info['pay_method'] == Models::PAY_WECHAT){
                    // 微信退款
                    $wx = new WxPay();
                    $result = $wx->WxRefund($info);
                    file_put_contents(ROOT_PATH.'/wxpay/logs/log1.txt',var_export($result,true).'\r\n',FILE_APPEND);
                    if(($result['return_code']=='SUCCESS') && ($result['result_code']=='SUCCESS')){
                        // 退款成功

                    }else if(($result['return_code']=='FAIL') || ($result['result_code']=='FAIL')){
                        // 退款失败
                        throw new \LogicException($result['return_msg'],$result['return_code']);
                    }else{
                        throw new \LogicException('操作失败',1010);
                    }
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($result));
        }
    }

    /**
     * 选择代金券
     * @return \think\response\Json
     */
    public function chooseVoucher(){
        if(request()->isPost()){
            try{
                // 登录验证
                $params = self::checkLogin(['equipment','encrypt','voucher_id']);
                //选择代金券
                $issue = new Models('voucher_issue');
                $info = $issue->joinOne([['voucher b','a.voucher_id = b.id','left']],['a.uid'=>$params['uid'],'a.voucher_id'=>$params['voucher_id'],'a.status'=>Models::VOUCHER_USE_NOT],'a.id,b.price');
                if(!$info){
                    throw new \LogicException('代金券不存在或已使用',1035);
                }
                $order = new Models('order');
                $order_info = $order->_find($params['order_id']);
                if(!$order_info){
                    throw new \LogicException('订单不存在',1036);
                }
                // 弱网防止重复操作
                if($order_info['voucher_id'] == 0){
                    // 订单使用代金券
                    $bool = $order->_save(['id'=>$params['order_id'],'voucher_id'=>$params['voucher_id'],'pay_amount'=>['exp','pay_amount-'.$info['price']]]);
                    // 修改代金券状态
                    $bool1 = $issue->_save(['id'=>$info['id'],'status'=>Models::VOUCHER_USE_YES]);
                    if(!$bool || !$bool1){
                        throw new \LogicException('操作失败',1010);
                    }
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult(['order_id'=>$params['order_id']]));
        }
    }

    /**
     * 选择支付方式并付款
     * @return \think\response\Json
     */
    public function choosePayment(){
        if(request()->isPost()){
            try{
                // 登录验证
                $params = self::checkLogin(['equipment','encrypt','subject','pay_method']);
                // 获取订单信息
                $order = new Models('order');
                $info = $order->_find($params['order_id']);
                // 修改支付方式
                $bool = $order->_save(['id'=>$params['order_id'],'pay_method'=>$params['pay_method']]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
                $response = null;
                if($params['pay_method'] == Models::PAY_ALIPAY){
                    // 支付宝支付
                    $alipay = new AliPay();
                    $response = $alipay->aliPay($params['subject'],$info['order_no'],$info['pay_amount']);
                }
                if($params['pay_method'] == Models::PAY_WECHAT){
                    // 微信支付
                    $wxpay = new WxPay();
                    $response = $wxpay->wxPay(['body'=>$params['subject'],'out_trade_no'=>$info['order_no'],'total_fee'=>$info['pay_amount']]);
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($response));
        }
    }

    /**
     * 检查支付订单状态
     * @return \think\response\Json
     */
    public function checkPayStatus(){
        if(request()->isPost()){
            $params = input('param.');
            try{
                $order = new Models('order');
                $info = $order->_find($params['order_id']);
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult(['status'=>$info['status']]));
        }
    }

    /**
     * 选择营销接待
     * @return \think\response\Json
     */
    public function chooseSeller(){
        if(request()->isPost()){
            try{
                // 登录验证
                $params = self::checkLogin(['equipment','encrypt','seller_id']);
                $order = new Models('order');
                // 修改营销人员
                $bool = $order->_save(['id'=>$params['order_id'],'sid'=>$params['seller_id']]);
                if(false === $bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult(['order_id'=>$params['order_id']]));
        }
    }

    /**
     * 订单表添加纪录
     * @param $params
     * @return int|string
     */
    public function orderAdd($params){
        // 获取默认销售信息
        $list = User::seller(['business_id'=>$params['bid']]);
        $order = new Models('order');
        $add = [
            'uid'          => $params['uid'],
            'bid'          => isset($params['bid']) ? $params['bid'] : 0,
            'aid'          => isset($params['id']) ? $params['id'] : 0,
            'sid'          => isset($params['sid']) ? $params['sid'] : $list[0]['id'],
            'pid'          => isset($params['product_id']) ? $params['product_id'] : 0,
            'type_id'      => $params['type_id'],
            'table_id'     => isset($params['table_id']) ? $params['table_id'] : 0,
            'order_no'     => date('YmdHis').rand(0001,9999),   // 生成订单号
            'order_amount' => $params['order_amount'],
            'pay_amount'   => $params['order_amount'],
            'create_time'  => time(),
        ];
        $order_id = $order->_add($add);
        if(!$order_id){
            throw new \LogicException('操作失败',1010);
        }
        return $order_id;
    }

    /**
     * 订单商品关系表批量插入纪录
     * @param $params
     */
    public function orderGoodsAdd($params){
        $order_goods = new Models('order_goods');
        $goods = json_decode(html_entity_decode($params['goods']),true);
        foreach($goods as $k=>$v){
            $add[] = ['oid'=>$params['oid'],'gid'=>$k,'qty'=>$v];
        }
        $bool = $order_goods->_addAll($add);
        if(!$bool){
            throw new \LogicException('操作失败',1010);
        }
    }
}